//
//  MFViewController.m
//  MFZSDK
//
//  Created by RJPan on 05/17/2024.
//  Copyright (c) 2024 RJPan. All rights reserved.
//

#import "MFViewController.h"

#import <MFZSDK/MFSDKManager.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <CommonCrypto/CommonDigest.h>
#import <sys/utsname.h>
#import <StoreKit/StoreKit.h>
#import <MFZSDK/MFSDKAppEvents.h>
#import <MFZSDK/MFCacheData.h>
#import <AdSupport/AdSupport.h>
#import <FirebaseMessaging/FirebaseMessaging.h>

@interface MFViewController ()

@property (weak, nonatomic) IBOutlet UILabel *desLabel;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSDictionary *userInfo;//用户信息
@property (nonatomic, strong) NSArray *dataArray;

@property (nonatomic, strong) NSString *uuid;
@property (nonatomic, strong) UILabel *label;

@end

@implementation MFViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dataArray = @[@"静默登录", @"账号登录", @"账号绑定", @"显示悬浮球", @"隐藏悬浮球", @"支付", @"获取商品价格", @"新手事件", @"自定义事件", @"评价", @"客服", @"个人中心", @"粉丝页", @"游戏圈", @"原生分享", @"分享-Facebook图片", @"分享-Facebook链接分享", @"分享-line图片分享", @"分享-line链接分享", @"社群-Facebook", @"社群-Discord", @"加载web页", @"条款，协议等", @"IP地区", @"绑定手机号", @"上传邮箱", @"上报缓存数据到魔方服务器", @"从魔方服务器获取缓存数据", @"上报游戏数据到iCloud", @"从iCloud获取游戏数据"];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
    
    self.label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 50)];
    self.label.text = @"跑马灯效果示例跑马灯效果示例跑马灯效果示例跑马灯效果示例跑马灯效果示例跑马灯效果示例";
    [self.label sizeToFit];
//    [self.view addSubview:self.label];
//
//    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:0.02 target:self selector:@selector(moveLabel:) userInfo:nil repeats:YES];
    
    //魔方回调
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mfCallBack:) name:MFCallBack object:nil];
}

//移动UILabel的位置
- (void)moveLabel:(NSTimer *)timer {
    CGFloat x = self.label.frame.origin.x;
    CGFloat y = self.label.frame.origin.y;
    self.label.frame = CGRectMake(x - 1, y, self.label.frame.size.width, self.label.frame.size.height);
    if (self.label.frame.origin.x + self.label.frame.size.width < 0) {
        self.label.frame = CGRectMake(self.view.bounds.size.width, self.label.frame.origin.y, self.label.frame.size.width, self.label.frame.size.height);
    }
}

//SDK回调
- (void)mfCallBack:(NSNotification *)noti {
    NSLog(@"回调参数：%@", noti.userInfo);
    NSDictionary *resultDic = noti.userInfo;
    MFCallBackType state = [[resultDic objectForKey:@"MFCBType"] integerValue];
    switch (state) {
        case login_success: {//登录成功
            NSDictionary *dictionary = resultDic[@"user"];
            NSString *singnatureOne = [self signature:dictionary];//签名
            if([resultDic[@"signature"] isEqualToString:singnatureOne]){//验证签名是否一致
                NSLog(@"签名一致,游戏登录成功:%@", [FIRMessaging messaging].FCMToken);
                self.uuid = dictionary[@"uuid"];
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.desLabel.text = [NSString stringWithFormat:@"登录成功:%@", dictionary[@"username"]];
                });
                /* 登陆成功后，将用户在游戏内的信息传入SDK
                 * mfGetUserUID:SDK登录返回的uuid
                 * appName:     游戏名称
                 * sid:         区服id
                 * sname:       区服名称
                 * role:        用户在游戏内的角色名
                 * isNew:       是否是该区服新用户；NO：老用户；YES：新用户
                 */
                [MFSDKManager mfGetUserUID:dictionary[@"uuid"] appName:@"魔方test" serverId:@"s1" sname:@"魔方" role:@"角色名" isServerNew:YES];
            }
        }
            break;
        case login_fail: {//登录失败
            NSLog(@"%@", resultDic[@"msg"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"登录失败:%@", resultDic[@"msg"]];
            });
        }
            break;
        case accountChange_success: {//切换账号成功
            NSLog(@"%@", resultDic);
            NSDictionary *dictionary = resultDic[@"user"];
            NSString *singnatureOne = [self signature:dictionary];//签名
            if([resultDic[@"signature"] isEqualToString:singnatureOne]){//验证签名是否一致
                NSLog(@"签名一致,切换账号成功");
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.desLabel.text = [NSString stringWithFormat:@"切换账号成功:%@", dictionary[@"username"]];
                });
                /* 登陆成功后，将用户在游戏内的信息传入SDK
                 * mfGetUserUID:SDK登录返回的uuid
                 * appName:     游戏名称
                 * sid:         区服id
                 * sname:       区服名称
                 * role:        用户在游戏内的角色名
                 * isNew:       是否是该区服新用户；NO：老用户；YES：新用户
                 */
                [MFSDKManager mfGetUserUID:dictionary[@"uuid"] appName:@"魔方test" serverId:@"s1" sname:@"魔方" role:@"角色名" isServerNew:YES];
            }
        }
            break;
        case accountChange_fail: {//切换账号失败
            NSLog(@"%@", resultDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"切换账号失败:%@", resultDic[@"msg"]];
            });
            if ([resultDic[@"msg"] isEqualToString:@"请先调用静默登录接口"]) {
                [MFSDKManager mfinitAndLogin];//调用静默登录接口
            }
        }
            break;
        case bind_success: {//绑定成功
            NSLog(@"%@", resultDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"绑定账号成功:%@", resultDic[@"user"][@"username"]];
            });
        }
            break;
        case bind_fail: {//绑定失败
            NSLog(@"%@", resultDic);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"绑定账号失败:%@", resultDic[@"msg"]];
            });
            if ([resultDic[@"msg"] isEqualToString:@"请先调用静默登录接口"]) {
                [MFSDKManager mfinitAndLogin];//调用静默登录接口
            }
            if ([resultDic[@"msg"] isEqualToString:@"已绑定账号"]) {
                NSLog(@"已绑定过账号，不能重复绑定");
            }
        }
            break;
        case user_banned: {//账号被禁用(请调用切换账号接口)
            NSLog(@"%@", resultDic[@"msg"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"账号被禁用:%@", resultDic[@"msg"]];
                [MFSDKManager mfSwitchAccount];//切换账号
            });
        }
            break;
        case applePay_success: {//支付成功
            NSLog(@"%@", resultDic[@"msg"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"apple支付成功:%@", resultDic[@"orderId"]];
            });
        }
            break;
        case applePay_fail: {//支付失败
            NSLog(@"%@", resultDic[@"msg"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"apple支付失败:%@", resultDic[@"msg"]];
            });
        }
            break;
        case products_price: {//获取商品价格
            NSLog(@"获取商品价格:%@", resultDic[@"data"]);
            NSDictionary *priceDic = resultDic[@"data"];
            NSString *string = @"";
            if ([priceDic count] == 0) {
                NSLog(@"没有请求到商品");
                string = @"没有请求到商品";
            } else {
                for (NSString *key in [priceDic allKeys]) {
                    string = [NSString stringWithFormat:@"%@%@:%@,\n", string, key, priceDic[key]];
                }
            }
            UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"提示" message:string preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
            [alertC addAction:action];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self presentViewController:alertC animated:YES completion:nil];
            });
        }
            break;
        case receive_messages: {//收到消息
            NSLog(@"%@", resultDic[@"data"]);
            dispatch_async(dispatch_get_main_queue(), ^{
                self.desLabel.text = [NSString stringWithFormat:@"收到新客服消息数:%@", resultDic[@"data"][@"msg_cs"]];
            });
        }
            break;
        default:
            break;
    }
}

- (void)dealloc {
    //移除
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MFCallBack object:nil];
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = self.dataArray[indexPath.row];
    return cell;
}


#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0://静默登录
            [MFSDKManager mfinitAndLogin];
            break;
        case 1://账号登录
            [MFSDKManager mfSwitchAccount];
            break;
        case 2://账号绑定
            [MFSDKManager mfBindAccount];
            break;
        case 3://显示悬浮球
            [MFSDKManager showFloatView];
            break;
        case 4://隐藏悬浮球
            [MFSDKManager hideFloatView];
            break;
        case 5://支付
            [MFSDKManager payWithProductID:@"com.morefunsdk.test.diamond1" producuName:@"fmucqu" productCount:@"1" productPrice:@"0.99" userLevel:0 exInfor:@"60砖石"];
            break;
        case 6://获取商品价格
            [MFSDKManager getProductLocalPriceWithProductIds:@[@"com.morefunsdk.test.diamond1"]];
            break;
        case 7://新手事件
            [MFSDKManager newUserEvent];
            break;
        case 8://自定义事件
            [MFSDKManager logEventsWithEventName:@"eventName"];
            break;
        case 9://评价
            [self inviteUsersRate];
            break;
        case 10://客服
            [MFSDKManager openCustomerServiceCenter];
            break;
        case 11://个人中心
            [MFSDKManager openUserCenter];
            break;
        case 12://粉丝页
            [MFSDKManager openFanPage];
            break;
        case 13://游戏圈
            [MFSDKManager openGameHub];
            break;
        case 14://原生分享
        {
            NSString *textToShare = @"要分享的文本内容";//分享文本
            UIImage *imageToShare = [UIImage imageNamed:@"1.png"];//分享图片
            NSURL *urlToShare = [NSURL URLWithString:@"https://www.baidu.com"];//分享链接
            NSArray *items = @[textToShare, imageToShare, urlToShare];//分享内容：可分享以上三种形式，也可分享任何一种，或两两组合
            [[MFShareManager defaultManage] nativeShareWithItems:items viewController:self result:^(BOOL completed) {
                if (completed) {
                    NSLog(@"分享完成");
                } else {
                    NSLog(@"分享未完成");
                }
            }];
        }
            break;
        case 15://分享-Facebook图片
        {
            [[MFShareManager defaultManage] fbShareWithImage:[UIImage imageNamed:@"1.png"] result:^(id  _Nonnull result) {
                if ([result[@"code"] isEqualToString:@"0"]) {
                    NSLog(@"fb图片分享成功");
                } else {
                    NSLog(@"fb图片分享失败：%@", result[@"msg"]);
                }
            }];
        }
            break;
        case 16://分享-Facebook链接分享
        {
            [[MFShareManager defaultManage] fbShareWithUrl:@"https://www.baidu.com" result:^(id  _Nonnull result) {
                if ([result[@"code"] isEqualToString:@"0"]) {
                    NSLog(@"fb链接分享成功");
                } else {
                    NSLog(@"fb链接分享失败：%@", result[@"msg"]);
                }
            }];
        }
            break;
        case 17://分享-line图片分享
        {
            [[MFShareManager defaultManage] lineShareWithUrlString:@"https://www.baidu.com" result:^(BOOL result) {
                if (result) {
                    NSLog(@"line链接分享成功");
                } else {
                    NSLog(@"line链接分享失败");
                }
            }];
        }
            break;
        case 18://分享-line链接分享
        {
            [[MFShareManager defaultManage] lineShareWithUrlString:@"https://www.baidu.com" result:^(BOOL result) {
                if (result) {
                    NSLog(@"line链接分享成功");
                } else {
                    NSLog(@"line链接分享失败");
                }
            }];
        }
            break;
        case 19://社群-Facebook
            {
                BOOL fbResult = [MFSDKManager mfOpenFBPageWithPageID:@"101789568871257" pageUrl:@"https://www.facebook.com/taptapuniverse"];
                NSLog(@"加载facebook社群页：%d", fbResult);
            }
            break;
        case 20://社群-Discord
        {
            BOOL result = [MFSDKManager mfOpenPage:@"https://discord.gg/86AKWWJTxs"];
            NSLog(@"打开discord社群：%d", result);
        }
            break;
        case 21://加载web页
            [MFSDKManager mfOpenUrl:@"https://www.baidu.com"];
            break;
        case 22://条款，协议等
            //type 类型(枚举值)：Terms：服务条款；Policy：隐私政策；Rules：管理规定
            [MFSDKManager showAgreementWithViewContrller:self type:Policy];
            break;
        case 23://IP地区
        {
            [MFSDKManager queryLocalCountryWithSuccess:^(id obj) {
                NSLog(@"====%@", obj);
            } fail:^(NSError *error) {
                NSLog(@"----%@", error);
            }];
        }
            break;
        case 24://绑定手机号
        {
            [MFSDKManager mfBindPhoneWithVC:self results:^(NSDictionary *resultDic) {
                NSLog(@"绑定手机号:%@", resultDic);
                if ([resultDic[@"code"] isEqualToString:@"10000"]) {
                    NSLog(@"绑定手机号成功");
                } else if ([resultDic[@"code"] isEqualToString:@"4000"]) {
                    NSLog(@"取消绑定");
                } else if ([resultDic[@"code"] isEqualToString:@"4001"]) {
                    NSLog(@"请先登录SDK");
                }
            }];
        }
            break;
        case 25://上传邮箱
            [MFSDKManager updateEmail:@"xxxxxx@gmail.com"];
            break;
        case 26://上报缓存数据到魔方服务器
        {
            //上传数据:data中建议不要包含特殊字符（%，空格，&等）
            NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
            NSDictionary *dic = @{@"data_type": @"purchase",@"order_id": @"G20220331180639qQln3vDev",@"total_fee":@0.99,@"product_id": @"com.morefunsdk.test.diamond1",@"uuid": @"5685a5c1133d44eda574bdaec857e1cb",@"extra": @"5ae5f1a"};
            [MFCacheData mfSetCachedataWithDeviceId:idfa cacheId:@"1" data:[self convertToJsonData:dic] result:^(NSDictionary * _Nonnull result) {
                if ([result[@"status"] isEqualToString:@"success"]) {
                    NSLog(@"上传数据成功：%@", result[@"message"]);
                } else {
                    NSLog(@"上传数据失败：%@", result[@"message"]);
                }
            }];
        }
            break;
        case 27://从魔方服务器获取缓存数据
        {
            NSString *idfa = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
            [MFCacheData mfGetCacheDataWithQuery:@"{\"data_type\":\"purchase\"}" deviceId:idfa page:@"1" size:@"30" sortType:Sort_ASC result:^(NSDictionary * _Nonnull result) {
                if ([result[@"status"] isEqualToString:@"success"]) {
                    NSLog(@"获取数据：%@", result[@"data"]);
                    NSArray *dataArray = result[@"data"][@"data"];
                    if ([dataArray count] > 0) {
                        NSLog(@"键值对:%@", dataArray[0]);
                        NSString *jsonStr = [self convertToJsonData:dataArray[0]];
                        NSLog(@"字符串：%@", jsonStr);
                    } else {
                        NSLog(@"数据为空");
                    }
                } else {
                    NSLog(@"获取数据失败：%@", result[@"message"]);
                }
            }];
        }
            break;
        case 28://上报游戏数据到iCloud
        {
            NSDictionary *dic = @{@"data_type": @"purchase",@"order_id": @"G20220331180639qQln3vDev",@"total_fee":@0.99,@"product_id": @"com.morefunsdk.test.diamond1",@"uuid": @"5685a5c1133d44eda574bdaec857e1cb",@"extra": @"5ae5f1a"};
            [MFCacheData setUpKeyValueICloudStoreWithKey:[NSString stringWithFormat:@"iCloudTest_%@_%@", [[NSBundle mainBundle] bundleIdentifier], self.uuid] value:[self convertToJsonData:dic]];
        }
            break;
        case 29://从iCloud获取游戏数据
        {
            NSString *jsonString = [MFCacheData getKeyValueICloudStoreWithKey:[NSString stringWithFormat:@"iCloudTest_%@_%@", [[NSBundle mainBundle] bundleIdentifier], self.uuid]];
            NSLog(@"从iCloud获取游戏数据：%@", jsonString);
        }
            break;
        default:
            break;
    }
}

#pragma mark - 应用评价

- (void)inviteUsersRate {
    //邀请用户对应用进行评价
    [MFSDKManager mfInviteUsersRateAlertWithTitle:@"您喜欢MFSDK吗？" desString:@"MFSDK需要您的鼓励哦" submitButton:@"评价" result:^(id obj) {
        if ([obj[@"type"] integerValue] == 0) {//评分
            int score = [obj[@"msg"] intValue];
            NSLog(@"选择评分:%d", score);
            if (score == 5) {//AppStore评分
                NSLog(@"AppStore评分");
            } else {
                NSLog(@"低于5星，去客服吐槽");
            }
        } else if ([obj[@"type"] integerValue] == 1) {//评分功能未开放
            NSLog(@"功能未开放");
        } else if ([obj[@"type"] integerValue] == 2) {//选择下次再说
            NSLog(@"选择下次再说");
        }
    }];
    
    //评价应用接口
    /*
     [MFSDKManager mfUserToAppStoreRateWithResult:^(id obj) {
     if ([obj[@"type"] integerValue] == 0) {//评分
     NSLog(@"%@", obj[@"msg"]);
     } else if ([obj[@"type"] integerValue] == 1) {//评分功能未开放
     NSLog(@"功能未开放");
     }
     }];
     */
}

#pragma mark - 签名验证

//签名验证
- (NSMutableString *)signature:(NSDictionary *)params {
    NSDictionary* dict   = params;
    //排序
    NSArray * sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(caseInsensitiveCompare:)];
    //NSLog(@"sortedKeys : %@",sortedKeys);
    NSArray * objects    = [dict objectsForKeys: sortedKeys notFoundMarker: [NSNull null]];
    //NSLog(@"objects : %@",objects);
    //连接字符串
    NSMutableString *str = [[NSMutableString alloc]init];
    for(id obj in objects){
        if (![obj isKindOfClass:[NSString class]]) {
            //NSLog(@"不是string类型的转换成string");
            NSString *transform = [NSString stringWithFormat:@"%@",obj];
            [str appendString:transform];
        }
        else {
            [str appendString:obj];
        }
    }
    [str appendString:@"EWTS1XURO809DH64KPB23AQVNI5GFZJ7CMYL"];
    //hash md5
    const char *cStr = [str UTF8String];
    unsigned char digest[16];
    
    CC_MD5(cStr,(CC_LONG)strlen(cStr), digest);
    
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++){
        [output appendFormat:@"%02x", digest[i]];
    }
    return output;
}

//字典转json字符串
- (NSString *)convertToJsonData:(NSDictionary *)dic {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    } else {
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    
    return mutStr;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
